package cn.tedu.charging.order.timer;

import cn.tedu.charging.common.pojo.po.ChargingBillExceptionPO;
import cn.tedu.charging.common.pojo.po.ChargingBillSuccessPO;
import cn.tedu.charging.order.mapper.BillExceptionMapper;
import cn.tedu.charging.order.mapper.BillSuccessMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class OrderTimerJob {
    //操作success订单
    @Autowired
    private BillSuccessMapper billSuccessMapper;
    // 操作exception
    @Autowired
    private BillExceptionMapper billExceptionMapper;
    //准备一个job-handler
    //order-status-check
    @XxlJob("order-status-check")
    public void checkOrderStatus(){
        log.debug("订单状态检查任务开始执行...");
        //1.拿到参数 billId xxl-job传递过来的 从上下文中获取
        String billId = XxlJobContext.getXxlJobContext().getJobParam();
        //2.查询successPO
        QueryWrapper<ChargingBillSuccessPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bill_id",billId);
        ChargingBillSuccessPO success = billSuccessMapper.selectOne(queryWrapper);
        Integer billStatus = success.getBillStatus();
        if(billStatus==1){
            //按照异常单,充电长时间未结束处理.立刻结束
            saveExceptionBill(billId);
            //修改订单状态 把status=1变成status=3
            updateBillStatus(billId,3);
            //将订单长时间未结束异常推送给用户 实时展示
            sendUserExceptionMessage(billId,success.getUserId());
            //TODO 枪状态修改
        }
    }

    private void updateBillStatus(String billId, int status) {
        //update charging_bill_success set bill_status=? where bill_id=?
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("bill_id",billId);
        updateWrapper.setSql("bill_status="+status);
        billSuccessMapper.update(null,updateWrapper);
    }

    private void saveExceptionBill(String billId) {
        //insert into charging_bill_exception
        //关于异常单的其他属性,可以通过创建任务传递param参数扩展
        ChargingBillExceptionPO exceptionPO = new ChargingBillExceptionPO();
        exceptionPO.setBillId(billId);
        exceptionPO.setCreateTime(new Date());
        billExceptionMapper.insert(exceptionPO);
    }

    private void sendUserExceptionMessage(String billId, Integer userId) {
        //TODO
    }
}
